from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from lib.common import AbstractHandler
import logging
app_logger = logging.getLogger("student")
import json
from django.core.cache import cache
from services.datamodel.student.models import mm_Student, mm_StudentAgent
from services.asyntask.paika_task import send_cards
import collections
from services.datamodel.setmeal.models import mm_SetMeal
from services.datamodel.vip.models import mm_UserAuthentication
import traceback


class Handler(AbstractHandler):

    def __init__(self):
        AbstractHandler.__init__(self, app_logger)

    @csrf_exempt
    def handle_esign_notify(self, request):
        app_logger.error("这是实名认证的回调")
        app_logger.error(json.loads(request.body))
        notify_data = json.loads(request.body)
        if notify_data['success']:
            userObj = mm_StudentAgent.filter(student_id=int(notify_data['state'])).values().first()
            if str(notify_data['type']) == "ORGANIZE":
                if userObj:
                    mm_StudentAgent.filter(student_id=int(notify_data['state'])).update(status=1,
                                                                                        org_id=notify_data['orgId'],
                                                                                        name=notify_data['orgName'])
                    # 发卡
                    datas = cache.get("user_meal_"+str(userObj['student_id']))
                    if datas:
                        kaihu = json.loads(datas)
                        meal_dict = mm_SetMeal.get_meal(special_status=1)[kaihu['level']]
                        set_meal_data = collections.defaultdict(list)
                        for v in meal_dict:
                            set_meal_data[v['serial_number']].append({'name': v['name'], 'nums': v['nums'],
                                                                      'goods_id': v['goods_id']})
                        app_logger.error("这是实名认证回调的派卡")
                        for v in set_meal_data[kaihu['set_meal']]:
                            send_ret = send_cards(userObj['student_id'], v['nums'], kaihu['expired_at'], kaihu['seller_id'], 6,
                                                  level=kaihu['level'], role_id=v['goods_id'],
                                                  seller_level=kaihu['seller_level'])
                            app_logger.error(send_ret)
                        mm_Student.filter(id=userObj['student_id']).update(level=kaihu['level'])
                        mm_Student.get_proxy_cert(mm_Student.get(id=userObj['student_id']))
                        cache.delete("user_meal_"+str(userObj['student_id']))
            if str(notify_data['type']) == "PERSON":
                if userObj:
                    mm_StudentAgent.filter(student_id=int(notify_data['state'])).update(status=1,
                                                                                        account_id=notify_data['accountId'])
                    datas = cache.get("user_meal_"+str(userObj['student_id']))
                    if datas:
                        kaihu = json.loads(datas)
                        if kaihu['level'] == 3:
                            meal_dict = mm_SetMeal.get_meal(special_status=1)[kaihu['level']]
                            set_meal_data = collections.defaultdict(list)
                            for v in meal_dict:
                                set_meal_data[v['serial_number']].append({'name': v['name'], 'nums': v['nums'],
                                                                          'goods_id': v['goods_id']})
                            app_logger.error("这是实名认证回调的派卡")
                            for v in set_meal_data[kaihu['set_meal']]:
                                send_ret = send_cards(userObj['student_id'], v['nums'], kaihu['expired_at'], kaihu['seller_id'],
                                                      6, level=kaihu['level'], role_id=v['goods_id'],
                                                      seller_level=kaihu['seller_level'])
                                app_logger.error(send_ret)
                            mm_Student.filter(id=userObj['student_id']).update(level=kaihu['level'])
                            mm_Student.get_proxy_cert(mm_Student.get(id=userObj['student_id']))
                            mm_StudentAgent.filter(student_id=int(notify_data['state'])).update(status=2)
                            cache.delete("user_meal_"+str(userObj['student_id']))
        return JsonResponse({"code": "200", "msg": "success"})

    @csrf_exempt
    def handle_signflows_notify(self, request):
        app_logger.error(json.loads(request.body))
        notify_data = json.loads(request.body)
        app_logger.error("电子合同返回11111")
        try:
            filowObj = mm_UserAuthentication.get_or_default(flow_id=notify_data['flowId'])
            if filowObj.status in [2, 3, 4]:
                return JsonResponse({"code": "200", "msg": "success"})
            if str(notify_data['action']) == "SIGN_FLOW_UPDATE":
                # userObj = mm_StudentAgent.filter(student_id=filowObj.student_id,
                #                                  account_id=notify_data['authorizedAccountId']).values().first()
                #  修改状态  以及发卡
                # if userObj:
                #     mm_StudentAgent.filter(student_id=userObj['student_id']).update(status=2)
                #     filowObj.status = 2
                #     filowObj.save()
                #     # 发卡
                #     datas = cache.get("user_meal_"+str(userObj['student_id']))
                #     kaihu = json.loads(datas)
                #     meal_dict = mm_SetMeal.get_meal(special_status=1)[kaihu['level']]
                #     set_meal_data = collections.defaultdict(list)
                #     for v in meal_dict:
                #         set_meal_data[v['serial_number']].append({'name': v['name'], 'nums': v['nums'],
                #                                                   'goods_id': v['goods_id']})
                #     for v in set_meal_data[kaihu['set_meal']]:
                #         user_cards_num_seller = mm_Student.getMyCardStats(kaihu['seller_id'], v['goods_id'])['balance']
                #         if user_cards_num_seller is None or user_cards_num_seller < v['nums']:
                #             app_logger.error("对不起， 您的余卡不足")
                #             #  这个状态会在上级买了卡之后自动扣卡后删除
                #             filowObj.status = 6
                #             filowObj.save()
                #             cache.set("faka_status_"+str(userObj['student_id']), 1, None)
                #             return JsonResponse({"code": "200", "msg": "success"})
                #     app_logger.error("这是签名回调的派卡")
                #     for v in set_meal_data[kaihu['set_meal']]:
                #         send_ret = send_cards(userObj['student_id'], v['nums'], None, kaihu['seller_id'], 2,
                #                               level=kaihu['level'], role_id=v['goods_id'],
                #                               seller_level=kaihu['seller_level'])
                #         app_logger.error(send_ret)
                #     mm_Student.filter(id=userObj['student_id']).update(level=kaihu['level'])
                #     mm_Student.get_proxy_cert(mm_Student.get(id=userObj['student_id']))
                #     cache.delete("user_meal_"+str(userObj['student_id']))
                #     return JsonResponse({"code": "200", "msg": "success"})
                # else:
                filowObj.status = 1
                filowObj.save()
            if str(notify_data['action']) == "SIGN_FLOW_FINISH":
                if notify_data['flowStatus'] == "2":
                    userObj = mm_StudentAgent.filter(student_id=filowObj.student_id).values().first()
                    #  修改状态  以及发卡
                    if userObj:
                        mm_StudentAgent.filter(student_id=userObj['student_id']).update(status=2)
                        filowObj.status = 2
                        filowObj.save()
                        # 发卡
                        datas = cache.get("user_meal_"+str(userObj['student_id']))
                        kaihu = json.loads(datas)
                        meal_dict = mm_SetMeal.get_meal(special_status=1)[kaihu['level']]
                        set_meal_data = collections.defaultdict(list)
                        for v in meal_dict:
                            set_meal_data[v['serial_number']].append({'name': v['name'], 'nums': v['nums'],
                                                                      'goods_id': v['goods_id']})
                        for v in set_meal_data[kaihu['set_meal']]:
                            user_cards_num_seller = mm_Student.getMyCardStats(kaihu['seller_id'], v['goods_id'])['balance']
                            if user_cards_num_seller is None or user_cards_num_seller < v['nums']:
                                app_logger.error("对不起， 您的余卡不足")
                                #  这个状态会在上级买了卡之后自动扣卡后删除
                                filowObj.status = 6
                                filowObj.save()
                                cache.set("faka_status_"+str(userObj['student_id']), 1, None)
                                return JsonResponse({"code": "200", "msg": "success"})
                        app_logger.error("这是签名回调的派卡")
                        for v in set_meal_data[kaihu['set_meal']]:
                            send_ret = send_cards(userObj['student_id'], v['nums'], None, kaihu['seller_id'], 2,
                                                  level=kaihu['level'], role_id=v['goods_id'],
                                                  seller_level=kaihu['seller_level'])
                            app_logger.error(send_ret)
                        mm_Student.filter(id=userObj['student_id']).update(level=kaihu['level'])
                        mm_Student.get_proxy_cert(mm_Student.get(id=userObj['student_id']))
                        cache.delete("user_meal_"+str(userObj['student_id']))
                        return JsonResponse({"code": "200", "msg": "success"})

                if notify_data['flowStatus'] == "3":
                    filowObj.status = 3
                    filowObj.save()

                if notify_data['flowStatus'] == "5":
                    filowObj.status = 5
                    filowObj.save()

                if notify_data['flowStatus'] == "7":
                    filowObj.status = 7
                    filowObj.save()
            return JsonResponse({"code": "200", "msg": "success"})
        except:
            err = traceback.format_exc()
            app_logger.error("电子合同返回报错")
            app_logger.error(err)
            return JsonResponse({"code": "200", "msg": "success"})

esign_handler = Handler()